import { login } from '@/api/user'
import { Toast } from 'vant'

const userModule = {
  state: {
    username: localStorage.getItem('username') || '',
    avatarUrl: localStorage.getItem('avatarUrl') || '',
    token: localStorage.getItem('token') || '' // 令牌
  },
  mutations: {
    SET_USERNAME (state, payload) {
      state.username = payload
    },
    SET_AVATARURL (state, payload) {
      state.avatarUrl = payload
    },
    SET_TOKEN (state, payload) {
      state.token = payload
    }
  },
  actions: {
    // 异步登录，用于将登录成功后的用户状态数据保存到 state 中
    // context 是与 store 有着相同属性与方法结构的对象
    // payload 是用户信息对象，包含用户名与密码
    async loginAsync (context, payload) {
      try {
        const result = await login(payload)
        // 登录成功，则将响应的用户数据保存到状态中
        // action 中不能直接更新状态，仍然需要提交 mutation
        context.commit('SET_USERNAME', result.username)
        context.commit('SET_AVATARURL', result.avatarUrl)
        context.commit('SET_TOKEN', result.token)
        return {
          isLogin: true
        }
      } catch (error) {
        Toast.fail({
          message: error.message
        })
      }
    }
  }
}

export default userModule
